package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.domain.mongo.*;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.service.mongo.MovementService;
import com.itheima.util.ConstantUtil;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MovementServiceImpl implements MovementService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    /**
     * 保存动态信息
     *
     * @param movement 动态对象
     */
    @Override
    public void save(Movement movement) {
        //填充发布时间数据
        movement.setCreated(System.currentTimeMillis());
        movement.setPid(idService.getNextId(ConstantUtil.MOVEMENT_ID));
        //1.存入动态详情表
        mongoTemplate.save(movement);
        //2.获取存入详情表数据的id
        ObjectId publishId = movement.getId();
        //3.将数据存入自己的动态表,方便查询
        //表名为movement_mine_自己的userId
        MyMovement myMovement = new MyMovement();
        //设置发布动态的id
        myMovement.setPublishId(publishId);
        //设置发布时间
        myMovement.setCreated(System.currentTimeMillis());
        //保存到我的动态表
        mongoTemplate.save(myMovement, ConstantUtil.MOVEMENT_MINE + movement.getUserId());
        //4.查询朋友表
        Query query = new Query(Criteria.where("userId").is(movement.getUserId()));
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        //遍历朋友集合
        for (Friend friend : friendList) {
            //将数据插入到朋友的动态表中
            FriendMovement friendMovement = new FriendMovement();
            friendMovement.setUserId(movement.getUserId());
            friendMovement.setPublishId(movement.getId());
            friendMovement.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friendMovement, ConstantUtil.MOVEMENT_FRIEND + friend.getFriendId());
        }
    }

    /**
     * 审核动态,进行修改
     * @param movement 动态
     */
    @Override
    public void update(Movement movement) {
        //修改动态详情
        mongoTemplate.save(movement);
    }

    /**
     * 根据id 查询当前用户动态数据
     *
     * @param pageNum  页码
     * @param pagesize 每页显示的条数
     * @param userId   用户id
     * @return 用户的动态数据
     */
    @Override
    public PageBeanVo findAllMovements(Integer pageNum, Integer pagesize, Long userId) {
        //计算页码索引
        int startIndex = (pageNum - 1) * pagesize;
        //构建初选条件
        Query query = new Query()
                .with(Sort.by(Sort.Order.desc("created")))
                .skip(startIndex).limit(pagesize);
        //查询我的动态数据
        List<MyMovement> myMovementList = mongoTemplate.find(query, MyMovement.class, ConstantUtil.MOVEMENT_MINE + userId);
        //
        List<Movement> movementList = new ArrayList<>();
        //遍历我的动态表
        for (MyMovement myMovement : myMovementList) {
            //从动态详情表中查出动态数据
            Movement movement = mongoTemplate.findById(myMovement.getPublishId(), Movement.class);
            if (movement.getState() == 1) {
                //将数据添加到集合中
                movementList.add(movement);
            }
        }
        System.out.println("我的动态" + movementList);
        //查询总记录数
        long count = mongoTemplate.count(query, ConstantUtil.MOVEMENT_MINE + userId);
        //返回pageBeanVo对象
        return new PageBeanVo(pageNum, pagesize, count, movementList);
    }

    /**
     * 查看好友动态
     *
     * @param pageNum     当前页码
     * @param pageSize    每页大小
     * @param loginUserId 登录用户id
     * @return 好友动态对象
     */
    @Override
    public PageBeanVo friendMovement(Integer pageNum, Integer pageSize, Long loginUserId) {
        int startIndex = (pageNum - 1) * pageSize;
        //查询当前用户的朋友圈表
        Query query = new Query()
                .with(Sort.by(Sort.Order.desc("created")))
                .skip(startIndex).limit(pageSize);
        List<FriendMovement> friendMovementList = mongoTemplate.find(query, FriendMovement.class, ConstantUtil.MOVEMENT_FRIEND + loginUserId);
        List<Movement> movementList = new ArrayList<>();
        System.out.println("朋友圈:" + friendMovementList);
        //如果朋友圈动态集合不为空
        if (CollectionUtil.isNotEmpty(friendMovementList)) {
            //遍历朋友的动态集合
            for (FriendMovement friendMovement : friendMovementList) {
                //查询朋友动态的详细信息
                Movement movement = mongoTemplate.findById(friendMovement.getPublishId(), Movement.class);
                if (movement.getState() == 1) {
                    movementList.add(movement);
                }
            }
        }
        //查询总记录数
        long count = mongoTemplate.count(query, ConstantUtil.MOVEMENT_FRIEND + loginUserId);
        //构建返回对象
        return new PageBeanVo(pageNum, pageSize, count, movementList);
    }

    /**
     * 查找推荐动态
     *
     * @param pageNum  当前页
     * @param pageSize 每页大小
     * @param userId   用户id
     * @return 推荐动态对象
     */
    @Override
    public PageBeanVo recommendMovement(Integer pageNum, Integer pageSize, Long userId) {
        int startIndex = (pageNum - 1) * pageSize;
        Query query = new Query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Order.desc("score")))
                .skip(startIndex).limit(pageSize);
        //查询推荐给当前用户的动态
        List<RecommendMovement> recommendMovementList = mongoTemplate.find(query, RecommendMovement.class);
        System.out.println(recommendMovementList);
        //
        List<Movement> movementList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(recommendMovementList)) {
            for (RecommendMovement recommendMovement : recommendMovementList) {
                //查询推荐动态的详细信息
                Movement movement = mongoTemplate.findById(recommendMovement.getPublishId(), Movement.class);
                movementList.add(movement);
            }
        }
        long count = mongoTemplate.count(query, RecommendMovement.class);
        return new PageBeanVo(pageNum, pageSize, count, movementList);
    }

    /**
     * 根据id查询动态信息
     *
     * @param movementId 动态id
     * @return 动态对象
     */
    @Override
    public Movement findMovement(String movementId) {
        return mongoTemplate.findById(movementId, Movement.class);
    }

    /**
     * 查询列表
     *
     * @param page        页码
     * @param pageSize    页面条数
     * @param commentType 操作类型
     * @return 相对应的操作列表
     */
    @Override
    public PageBeanVo findMovementByCommentType(Integer page, Integer pageSize, Integer commentType, Long userId) {

        int startIndex = (page - 1) * pageSize;
        Query query = new Query(Criteria.where("commentType").is(commentType)
                .and("publishUserId").is(userId))
                .with(Sort.by(Sort.Order.desc("created")))
                .skip(startIndex).limit(pageSize);
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);
        long count = mongoTemplate.count(query, Comment.class);
        return new PageBeanVo(page, pageSize, count, commentList);
    }

    /**
     * 查询动态信息
     *
     * @param page     页码
     * @param pageSize 每页条数
     * @param uid      用户id
     * @param state    状态
     * @return
     */
    @Override
    public PageBeanVo findMovementByUidAndState(Integer page, Integer pageSize, Long uid, Integer state) {
        int startIndex = (page - 1) * pageSize;
        Query query = new Query()
                .with(Sort.by(Sort.Order.desc("created")))
                .skip(startIndex).limit(pageSize);
        if (uid != null) {
            query.addCriteria(Criteria.where("userId").is(uid));
        }
        if (state != null) {
            query.addCriteria(Criteria.where("state").is(state));
        }
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);
        long count = mongoTemplate.count(query, Movement.class);
        return new PageBeanVo(page, pageSize, count, movementList);
    }

    //动态人工拒绝
    @Override
    public Map rejectUpdateMovement(String[] movementIds) {
        for (String movementId : movementIds) {
            Movement movement = mongoTemplate.findById(new ObjectId(movementId), Movement.class);
            movement.setState(2);
            mongoTemplate.save(movement);
        }
        Map<String,String> map =new HashMap();
        map.put("message","操作成功");
        return map;
    }

    //动态人工通过
    @Override
    public Map passUpdateMovement(String[] movementIds) {
        for (String movementId : movementIds) {
            Movement movement = mongoTemplate.findById(new ObjectId(movementId), Movement.class);
            movement.setState(1);
            mongoTemplate.save(movement);
        }
        Map<String,String> map = new HashMap<>();
        map.put("message","操作成功");
        return map;
    }
}
